<?php 
namespace clt\aisle;
/**
 * 缓存基础类
 */
use clt\Curl;
use clt\Mexception;
class unioncj{
	 public $pay_code = "unioncj";
	 public $api='https://chanpay.8bill.cn'; //接口地址
	 public $certType='02';   //证件类型 01：身份证02：军官证03：护照04：户口簿05：回乡证06：其他
     public function config(){
     	$i=0;
     	$modules[$i]['code']  = $this->pay_code ;
		$modules[$i]['jinjian']   =1 ;  //是否需要进件 0 不需要 1 需要
		/* 支付名称 */
	    $modules[$i]['name']    = 'CJ-银联快捷';

	    /* 描述对应的语言项 */
	    $modules[$i]['desc']    = 'CJ-银联快捷支付接口';

	    /* 作者 */
	    $modules[$i]['author']  = 'Perry Lin';


	    /* 版本号 */
	    $modules[$i]['version'] = 'V1.0.0';

	    /* 配置信息 */
	    $modules[$i]['config']  = array(
	        array('name' => 'merchantId',   'type' => 'text',   'value' => '', 'label'=>'商户号'),
	        array('name' => 'AESKEY',   'type' => 'text',   'value' => '', 'label'=>'AESKEY'),
	        array('name' => 'SHAKEY',   'type' => 'text',   'value' => '', 'label'=>'SHAKEY'),
	        array('name' => 'consRate',            'type' => 'text',   'value' => '', 'label'=>'费率(%)'),
	        array('name' => 'consFee',           'type' => 'text',   'value' => '', 'label'=>'手续费(元/笔)'),
	        array('name' => 'callback',           'type' => 'text',   'value' => 'http://'.$_SERVER['SERVER_NAME'].'/mobile/pay_callback.php', 'label'=>'支付成功跳转'),
	    );
	    /*接口通道*/
		$modules[$i]['aisle']  = array(
			array('pay_code'=> $this->pay_code ,'code'=>'pay01','payment'=>'unionpay','name'=>'CJ-银联快捷0001','status'=>0), 
			array('pay_code'=> $this->pay_code ,'code'=>'pay02','payment'=>'unionpay','name'=>'CJ-银联快捷0002','status'=>0), 
		);
     }
    /*常见订单编号 */
	public function create_orderID($prex="CJ"){
		return $prex."".time().rand(10000,99999);
	}
	/*获取银行卡简称*/
	public function getBankShowName($bankAccountNo){
		
		$url='https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo='.$bankAccountNo.'&cardBinCheck=true';
		$json = Curl::_get($url);
		if($json === false){
			return null;
		}	
		$json= json_decode(trim($json),true);
		return $json['bank'];
	}
	/**
	*  商户进件
	*  @param   array   $user      用户id
	*  @param   array   $config    用户支付配置信息
	*  return   array   code=> 0 失败 1成功 ，data=> 进件返回数据
	**/
	public function reg($user,$config){
		$data = array(
			'ordernumber' => $this->create_orderID(),
			'username' => $user['bankAccountName'],
			'userpid' =>  $user['identityNo'],
			'usercardno' => $user['bankAccountNo'],
			'bankname' => $user['openBankName'],
			'usertel' =>  $user['bindPhone'],
			'bankunion' => $user['cnapsNo'],
			'feerate' =>  $config['consRate'],
			'settlefee' => $config['consFee']*100,
			'province' =>  $user['province'],
			'city' => $user['city'],
			'bankcode' => substr($user['bankCode'],0, 3),
		);
		
		$bank = $this->getBankShowName($user['bankAccountNo']);
		$data['bankabbr'] = empty($bank) ? $bank : $user['bankabbr'];
		$base['merchantid'] = $config['merchantId'];
		$base['data'] = $this->mcrypt_encrypt($data,$config);
		$base['timestamp'] = date('YmdHis');
		$base['sign'] = $this->getSign($base['data'],$base['timestamp'],$config);
		
		//记录商户注册日志
		 $json_data = urlencode(json_encode($user));
		 $addtime = time();
		 $sql = "INSERT INTO ".$GLOBALS['ecs']->table('zhucelog')." (mobile,pay_code,go,addtime) VALUES('".$user['user_name']."','".$this->paycode."','".$json_data."','".$addtime."')";
		 $GLOBALS['db']->query($sql);
		 $zhuceid = mysql_insert_id();//接受返回数据更新数据库需要用到
		 $data = Curl::_post($this->api."/pay/newcjpay/merchant_reg",$base);
		
		$sdata = json_decode($data,true);
		 //记录返回注册信息日志
        //判断返回数据
		
	    if(isset($sdata['ret']) && $sdata['ret'] == 0)
		{
			$datas = $this->mcrypt_decrypt($sdata['data'],$config);
			$sdata = json_decode(trim($datas),true);
			if(isset($sdata['orderstate']) && $sdata['orderstate'] == 0){
				/*记录日志*/
				$sdata['paycode']=$this->paycode;
		        $json_arr = urlencode(json_encode($sdata));
		        $sql = "UPDATE ".$GLOBALS['ecs']->table('zhucelog')." SET `return`='".$json_arr."' WHERE id='".$zhuceid."'";
		        $GLOBALS['db']->query($sql);
		        /*记录返回数据*/
				$sql="INSERT INTO ".$GLOBALS['ecs']->table('mch_unioncj')." (pay_code,uid,mchtNo,mchtUid,bankAccountName,bankAccountNo,bankCode,cnapsName,openBankName) VALUE('unioncj','".$user['user_id']."','".$sdata['sub_merchant_id'] ."','".$sdata['sub_merchant_uid']."','".$user['bankAccountName']."','".$user['bankAccountNo']."','".$user['bankNo']."','".$user['cnapsName']."','".$user['openBankName']."')";
				$jin=$GLOBALS['db']->query($sql);
				$return['code']=1;  //返回成功标志
				$return['data']=array('err_paycode'=>'【CJ快捷支付】','err_msg'=>'进件成功');  //进件数据
				return $return;
			}else{
				if('商户已注册!请勿重复注册!' == $sdata['payinfo']){
					$return['code']=1;  //返回失败标志
					$return['data']=array('err_paycode'=>'【CJ快捷支付】','err_code'=>'','err_msg'=>$sdata['payinfo']); //进件失败数据
				}else{
					$return['code']=0;  //返回失败标志
					$return['data']=array('err_paycode'=>'【CJ快捷支付】','err_code'=>$sdata['orderstate'],'err_msg'=>$sdata['payinfo']); //进件失败数据
				}
				
				return $return;
			}
		}else{
			$return['code']=0;  //返回失败标志
			$return['data']=array('err_paycode'=>'【CJ快捷支付】','err_code'=>$sdata['ret'],'err_msg'=>$sdata['message']); //进件失败数据
			return $return;
		}
		
	}
	/*01通道*/
	public function pay01($order,$config){

		$row = db('aisle')->field('shua_rate,fee,settle_rate')->where(['pay_code'=>'unioncj','code'=>'pay01'])->find();
		if(empty($row)){
			return array('err_code'=>0,'err_msg'=>'支付通道已被关闭.');
		}
		$config['consRate'] = $row['shua_rate']*10;
		$config['consFee'] = $row['fee'];
		$config['settle_rate'] = $row['settle_rate'];
		return $this->payorder($order,$config,101001);
	}
	/*02通道*/
	public function pay02($order,$config){
		
		$row = db('aisle')->field('shua_rate,fee,settle_rate')->where(['pay_code'=>'unioncj','code'=>'pay02'])->find();
		if(empty($row)){
			return array('err_code'=>0,'err_msg'=>'支付通道已被关闭.');
		}
		$config['consRate'] = $row['shua_rate']*10;
		$config['consFee'] = $row['fee'];
		$config['settle_rate'] = $row['settle_rate'];
		return $this->payorder($order,$config,101002);
	}
	//盈起快捷
	public function payorder($order,$config,$cmd=1010){
		$data=array();
		$data['sub_merchant_id']=$config['mchtNo'];
		$data['ordernumber']=$order['order_no'];
		$data['amount']=$order['total_fee']*100;
		$data['usercardno']=$order['account']['bankAccountNo'];
		$data['username']=$order['account']['bankAccountName'];
		$data['usertel']=$order['account']['bindPhone'];
		$data['userpid'] = $order['account']['idNum'];
		$data['feerate'] = $config['consRate'];
		$data['settlefee'] = $config['consFee']*100;
		$data['body'] = "【CJ快捷支付】收款";
		//require_once(dirname(dirname(__FILE__)) . '/mobile/includes/IpLocation.php');
		//$new = new IpLocation(); 
		$ip = getIP();
		$city = $order['city']; 

		if(!empty($city)){
			$data['ip'] = $ip;
			$data['city'] = $city;
		}
		$data['cvn2']=$order['account']['cvn2'];
		$data['expdate'] = substr($order['account']['expDate'],2).substr($order['account']['expDate'],0,2);
		$data['backurl']  = U('wap/notice/unioncj');
		$base['merchantid'] = $config['merchantId'];
		$base['data'] = $this->mcrypt_encrypt($data,$config);
		$base['timestamp'] = date('YmdHis');
		$base['sign'] = $this->getSign($base['data'],$base['timestamp'],$config);
		$result = Curl::_post($this->api."/pay/newcjpay/merchant_pay/".$cmd,$base);
		$result = json_decode(trim($result),true);
		if(isset($result['ret']) && $result['ret'] == 0)
		{
			$sData = $this->mcrypt_decrypt($result['data'],$config);
			$Datas = json_decode(trim($sData),true);
			if(isset($Datas['orderstate']) && $Datas['orderstate']==0){
				$return['err_code']=0;
				$return['err_msg']='请求成功';
				$return['data']=array(
					'payMent'=>'unionpay',
					'fee'=>$config['fee'],
					'orderNo'=>$data['ordernumber'],
					'orderDate'=>time(),
					'single_fees' => $config['fee']-0.5,
				);
				return $return;
			}
			$result['message'] = $Datas['payinfo'];
		}
		$return=array();
		$return['err_code']=1;
		$return['err_msg']=$result['message'];
		$return['data']='';	
		//file_put_contents("logs/pay-".date('Y-m-d').".log",implode("\t\t\t", $return)."\n",FILE_APPEND);
		return $return;
	}	
	/*提现*/
	public function settle($order,$config,$t=400){
		$base['merchantid']=$config['merchantId'];
		$data['ordernumber']= create_orderID('TX');
		$data['sub_merchant_uid'] = $order['mch_id'];
		$amount = $order['total_fee']*(1-($order['shua_rate']/100));
		/*查找用户*/
		$user = db('users')->where(['user_id'=>$order['uid']])->find(); 
		$data['usercardno']=$user['bankAccountNo'];
		$data['username']=$user['bankAccountName'];
		$data['usertel']=$user['bindPhone'];
		$data['amount'] = intval($amount*100);//$amount-$config['consFee']-(($config['consRate']/1000)*$amount); //提现费用
		$data['userpid'] = $user['identityNo'];
		$data['bankunion'] = $user['cnapsNo'];
		$data['bankname'] = $user['openBankName'];
		$data['wallettype'] = $t;//400; //400 D0, 402 T1，默认400
		$base['data'] = $this->mcrypt_encrypt($data,$config);
		$base['timestamp']=date('YmdHis',time());
		$base['sign']=$this->getSign($base['data'],$base['timestamp'],$config);
		$result = Curl::_post($this->api."/pay/newcjpay/merchant/settle",$base);
		$result = json_decode(trim($result),true);
		if(isset($result['ret']) && $result['ret'] == 0)
		{
			$sData = $this->mcrypt_decrypt($result['data'],$config);
			$Datas = json_decode(trim($sData),true)
			if(isset($Datas['orderstate']) && $Datas['orderstate']==0){
				/*日志记录*/
				$data['create_time'] = time();
				$data['uid'] = $order['uid'];
				$data['amount'] = $data['amount']/100;//提现金额
				db('settlelogs')->insert($data);
				//成功返回该接口结算费率和刷卡费率用于计算佣金
				$return=array();
				$return['err_code']=0;
				$return['err_msg']='请求成功';
				$fees = $data['amount'];
				/*消息提示*/
				$token = db('weixin_code')->where(['id'=>$order['wehcat_id']])->value('token');
				sendMessage($token,$order['sub_openid'], 'text', array('content' => "收款通知:\n收款金额为".$order['total_fee']."元已到账,请注意查收..."));
				return $return;
			}
			$result['message'] = $Datas['message'];
		}	
		$return=array();
		$return['err_code']=1;
		$return['err_msg']=$result['message'];
		$return['data']='';	
		
		return $return;
	}
	/*应答回调*/
	public function respon($data){
	
		$payment = new \app\wap\model\Payment;
		$config = $payment->getConfig($this->pay_code);
		$sign = $this->getSign($data['data'],$data['timestamp'],$config);
		if($sign == $data['sign']){
			$results = $this->mcrypt_decrypt($data['data'],$config);
			$results = json_decode(trim($results),1);

			if(isset($results['respcode']) && $results['respcode'] == 0){
				sleep(3);
				//检查订单是否已经处理
				$orderm = new \app\wap\model\Orders;
				$order  =$orderm->where(['order_no'=>$results['ordernumber']])->find();
				if($order['settle_status'] == 1){
					return true;
				}
				$config['mchtNo'] = $order['mch_id'];
				$result = $this->settle($order,$config);
				if($result['err_code'] == 0){
					//此处更改订单状态并计算佣金
					$content=$result['err_msg'];
					$orderm->order_paid($order['id'],5,$order['total_fee'],$content);
				}else{
					$content=$result['err_msg'];
					//$orderm->order_paid($dbres['id'],6,$dbres['total_fee'],$content);
					if($order['order_status'] != 6){
						/*消息提示*/
						$token = db('weixin_code')->where(['id'=>$order['wehcat_id']])->value('token');
						sendMessage($token,$order['sub_openid'], 'text', array('content' => "收款失败通知:\n收款金额为".$order['total_fee']."元,银行处理失败,请联系客服处理..."));
					}
				}
				// $sql = "INSERT INTO ".$GLOBALS['ecs']->table('pay_log')." (orderNo,order_amount,pay_amount,content,cashStatus) VALUES('".$results['ordernumber'] ."','".$dbres['total_fee']."','".$dbres['total_fee']."','".$content."','5')";
				// $GLOBALS['db']->query($sql);
				return $result; //$result = $this->settle($order,$temp);
			}
		}
	}
	/*钱包查询*/
	public function quickpayBalance($config){
		$data = array(
			'ordernumber' => create_orderID('CJ'),
			 'sub_merchant_uid' => $config['mchtNo'],
			);
		$base['merchantid'] = $config['merchantId'];
		$base['data'] = $this->mcrypt_encrypt($data,$config);
		$base['timestamp']=date('YmdHis',time());
		$base['sign']=$this->getSign($base['data'],$base['timestamp'],$config);
		$result = Curl::_post($this->api."/pay/newcjpay/merchant/wallet",$base);
		$result = json_decode(trim($result),true);
		if(isset($result['ret']) && $result['ret'] == 0){
			$sData = $this->mcrypt_decrypt($result['data'],$config);
			$Datas = json_decode(trim($sData),true);
			if(isset($Datas['orderstate']) && $Datas['orderstate'] == 0){
				$return['err_code']=0;
				$return['quickpayBalance']=$Datas['quickpayBalance'];
				$return['quickpayD0Balance'] = $Datas['quickpayD0Balance'];
				$return['quickpayT1Balance'] = $Datas['quickpayT1Balance'];
				return $return;
			}
			$result['message'] = $Datas['payinfo'];
		}
		return array(
				'err_code'=>1,
				'err_msg'=>$result['message'],
			);
	}
	/*获取到签名*/
	public function getSign($data,$timestamp=null,$config=array()){
		return hash('sha256',$config['SHAKEY'].$config['merchantId'].$data.$timestamp.$config['SHAKEY']);
	}
	/*数据加密*/
	public function mcrypt_encrypt($data,$config=array()){
		$str_padded = createDataString($data, false, false);
        if (strlen($str_padded) % 16) {
            $str_padded = str_pad($str_padded,strlen($str_padded) + 16 - strlen($str_padded) % 16, "\0");
        }
        return urlsafe_b64encode(openssl_encrypt($str_padded, "aes-128-cbc", $config['AESKEY'], OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $config['AESKEY']));
	}
	/*解密*/
	public function mcrypt_decrypt($data,$config=array()){
		$encryptedData = urlsafe_b64decode($data);
	    $decrypted = openssl_decrypt($encryptedData, 'aes-128-cbc',$config['AESKEY'], OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $config['AESKEY']);
	    return $decrypted;
	}
	/**/
	public function getCity($ip){
		$result = Curl::_get('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
		if($result != false){
			$result = json_decode(trim($result),true);
			return isset($result['data']['city']) ? $result['data']['city'] : '';
		}
		return '广州市';
	}
}